<template>
  <div class="page-warp h-f bg-grey-200">

    <div class="header-warp">
      <div class="sticky-headers sticky bg-white">
        <div class="form-header">
          <div class="search">
             <div class="col">
              <!-- <search-input v-model="queryParams.keyword" @search="searchList" :more="false"
                placeholder="请输入单据号"
              /> -->
              <search-input v-model="queryParams.iioCode" @search="searchList" placeholder="请输入单据号">
                <template #default>
                  <uni-forms
                    class-name="border-md"
                    label-position="top"
                  >
                    <uni-forms-item label="单号">
                      <uni-easyinput v-model="queryParams.iioCode" placeholder="请输入单据号"/>
                    </uni-forms-item>
                    
                    <!-- <uni-forms-item label="状态">
                      <uni-data-select
                        v-model="queryParams.iioState"
                        :localdata="stateList"
                        valueKey="value"
                        labelKey="text"
                         @change="handleSelect"
                      ></uni-data-select>
                    </uni-forms-item> -->
                    <uni-forms-item label="日期">
                      <!-- <uni-datetime-picker
                        type="datetimerange"
                        v-model="queryParams.planDate"
                        placeholder="请选择日期"
                        :defaultTime="planDefault"
                      /> -->
                      <uni-datetime-picker
                        v-model="queryParams.planDate"
                        type="daterange"
                        rangeSeparator="至"
                      />
                    </uni-forms-item>
					<uni-forms-item label="状态">
						<uni-data-select v-model="queryParams.iioState" :localdata="range"
							@change="changeIooState"></uni-data-select>
					</uni-forms-item>
                  </uni-forms>
                </template>
              </search-input>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="m-content">
      <div class="m-warp ">

        <template v-for="item in list.rows" :key="item['pso_id']">
          <collection-card
            :title-bg="false"
            prod
            :is-expand="true"
          >
            <template #title>
              <span>{{ item['pptl_code'] }}</span>
            </template>

            <collection-card-cell :prod="false"
                                  :state-type="proStateMap"
                                  :state="-1"
                                  :footer="true"
                                  footer-align="right"
            >
              <ul class="text-list line-h-lg">
                <li class="li-item">
                  <span class="title">业务类型：</span>
                  <span class="value">{{ item['iioBussTypeName'] }}</span>
                </li>
                <li class="li-item">
                  <span class="title">入库单号：</span>
                  <span class="value">{{ item['iioCode'] }}</span>
                </li>
                <li class="li-item">
                  <span class="title">入库时间：</span>
                  <span class="value">{{ item['iioApplyDate'] }}</span>
                </li>
                <li class="li-item">
                  <span class="title">业务单号：</span>
                  <span class="value">{{ item['iioBussCode'] }}</span>
                </li>
                <li class="li-item">
                  <span class="title">业务部门：</span>
                  <span class="value">{{ item['iioOrgName'] }}</span>
                </li>
                <li class="li-item">
                  <span class="title">业务员：</span>
                  <span class="value">{{ item['iioBussManName'] }}</span>
                </li>
                <li class="li-item">
                  <span class="title">备注：</span>
                  <span class="value">{{ item['remark'] }}</span>
                </li>
              </ul>

              <template #footer>
                <div class="prod-footer">
                  <div class="footer-btn">
                    <button-circle type="primary"
                                   @click="viewForm(item)">详情
                    </button-circle>
                    <button-circle type="danger" @click="deleteForm(item)"
                                   v-if="+item['iioState'] === 0"
                                   style="margin-left: 12px;">删除
                    </button-circle>
                    <button-circle type="primary" @click="editForm(item)"
                                   v-if="+item['iioState'] === 0"
                                   style="margin-left: 12px;">{{ getButtonTitle }}
                    </button-circle>
                  </div>
                </div>
              </template>
            </collection-card-cell>
          </collection-card>
        </template>

        <LoadingFooter
          :data="list.rows"
          :total="list.total"
          :loading="loadingStore.ILOADING"
          @load="loadMore"
          :h-offset="44"
        />
      </div>


      <div class="form-footer" v-if="is_p_in">
        <div class="footer-warp">
          <div class="footer__btn">
            <div class="btn">
              <button
                class="uni-btn"
                type="primary"
                @click="additem(0)"
                :disabled="loadingStore.ILOADING"
                :loading="loadingStore.ILOADING"
              >
                新增
              </button>
            </div>
             <div class="btn">
              <button
                class="uni-btn"
                type="primary"
                @click="additem(1)"
                :disabled="loadingStore.ILOADING"
                :loading="loadingStore.ILOADING"
              >
                同步
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <ConfirmModal
      v-model="dialog.del.show"
      :message="dialog.del.msg"
      @change="onDelete"
    />
  </div>
</template>

<script setup>
import { computed, reactive, ref } from 'vue'
import { debounce } from 'radash'
import { PageUtil } from '@/utils/PageUtil'
import { onLoad, onPullDownRefresh, onReachBottom, onShow } from '@dcloudio/uni-app'
import { useLoading } from '../../../../../store/LoadingStore'
import CollectionCard from '../../../../../components/CollectionCard.vue'
import CollectionCardCell from '../../../../../components/CollectionCardCell.vue'
import LoadingFooter from '../../../../../components/LoadingFooter.vue'
import { PAGE_ENTRY_ARG, usePageParamHook } from '../../common/PageParam'
import { useStockStore } from '../../../../../store/StockStore'
import SearchInput from '../../../../../components/SearchInput2.vue'
import ButtonCircle from '../../../../../components/ButtonCircle.vue'
import ConfirmModal from '../../../../../components/ConfirmModel/ConfirmModal.vue'
import { useMessage } from '../../../../../store/MessageStore'
import moment from "dayjs";

//#region Refs

//#endregion Refs

//-----------------------------------------------------------------

//#region Const
const proStateMap = {
  0: ''
}
//#endregion Const

//-----------------------------------------------------------------

//#region Use
const {
  PAGE_HOOK_PARAM,
  setupPage,
  getButtonTitle
} = usePageParamHook()
const loadingStore = useLoading()
const stockStore = useStockStore()
//#endregion Use

//-----------------------------------------------------------------

//#region Data
const queryParams = reactive({
  limit: 1,
  size: 20,
  iioState:0
})

const list = reactive({
  rows: [],
  total: 0
})

const stateList = ref([
  { value: 0, text: '未生效' },
  { value: 1, text: '已生效' },
])

	const range = ref([{
			value: 0,
			label: "未生效"
		},
		{
			value: 1,
			label: "已生效"
		},
	])
	
	const changeIooState = (val) => {
		queryParams.iioState = val;
		console.log(val,'vallllllll')
	}

const planDefault = ref([])

const is_p_in = computed(()=>{
  const { __PAGE_ID } = PAGE_HOOK_PARAM

  return __PAGE_ID === PAGE_ENTRY_ARG.P_IN
})
//#endregion Data

//-----------------------------------------------------------------

//#region Method
const searchList = function(e) {
  const {value = ""} = e || {}
  loadingStore.NEW_LIST()
  queryParams.limit = 1
  // queryParams.keyword = value
  queryList()
}

const queryList = function() {
  debounceQuery()
}

const debounceQuery = debounce({ delay: 300 }, () => {
  loadingStore.SET_LOADING()
  const { API_TYPE, BUSS_TYPE } = PAGE_HOOK_PARAM || {}
  const { planDate } = queryParams
  const [buss_time_start = "", buss_time_end = ""] = planDate || []
  delete queryParams.planDate
  stockStore.getStorageList({
    API_TYPE,
    iioBussTypeCode: BUSS_TYPE,
    ...queryParams,
    // buss_time_start,
    // buss_time_end,
    startTime:buss_time_start?buss_time_start +' 00:00:00':'',
    endTime:buss_time_end?buss_time_end + ' 23:59:59':'',
  }).then((res) => {
    let {
      Rows = [], Total = 0
    } = res || {}
    if (loadingStore.isLoadMore(list.rows, Total)) {
      list.rows = list.rows.concat(Rows)
    } else {
      list.rows = Rows
    }
    list.total = Total
    loadingStore.FINISH_ALL()
    uni.stopPullDownRefresh()
  })
})

const loadMore = function() {
  if (loadingStore.ILOADING) {
    return
  }
  const { total = 0, rows = [] } = list
  if (loadingStore.hasMore(rows, total)) {
    queryParams.limit += 1
    debounceQuery()
  }
}

const handleSelect = function(val) {
  console.log("val: ", val)
  queryParams.iioState = val
}

const additem = function(i) {
  PageUtil.addEvent('mo-addingitem', () => {
  }, {
    route: '/pages/stocks/material/warehouse/in/formview',
    params: {
      row: {
        PAGE_HOOK_PARAM,
        __create: true,
        __sync: i === 1
      }
    }
  })
}

const viewForm = function(item) {
  PageUtil.addEvent(
    'material-in-formview-view',
    () => {
      queryList()
    }, {
      route: '/pages/stocks/material/warehouse/in/formview',
      params: {
        row: {
          ...item,
          PAGE_HOOK_PARAM,
          __view: true
        }
      }
    }
  )
}

const editForm = function(item) {
  PageUtil.addEvent(
    'material-in-formview',
    () => {
      queryList()
    }, {
      route: '/pages/stocks/material/warehouse/in/formview',
      params: {
        row: {
          ...item,
          PAGE_HOOK_PARAM
        }
      }
    }
  )
}


const dialog = reactive({
  del: {
    show: false,
    msg: '确定要删除吗?',
    row:{}
  }
})
const deleteForm = function(item) {
  dialog.del.show = true
  dialog.del.row = item
}
const msgStore = useMessage()
const onDelete = function(e) {
  if (!e) return
  const { iioId: id } = dialog.del.row || {};
  const { API_TYPE, BUSS_TYPE } = PAGE_HOOK_PARAM || {}
  stockStore.stockListDelete({
    API_TYPE,
    ids:[id]
  }).then(res=>{
    msgStore.success('删除成功')
    searchList()
  })
}


//#endregion Method

//-----------------------------------------------------------------

//#region Page Events
onLoad((params) => {
  let { row } = PageUtil.parseParam(params)
  setupPage(row)
  searchList()
  planDefault.value = defaultTime2359()
})

const defaultTime2359 = function () {
  const et = moment().format("YYYY-MM-DD 23:59:59")
  const st = moment(et).subtract(1, "day").format("YYYY-MM-DD 00:00:00")

  return [st, et]
}

onShow(() => {
  searchList()
})

onPullDownRefresh(() => {
  searchList()
})

onReachBottom(() => {
  loadMore()
  console.log('list bottom')
})
//#endregion Page Events
</script>

<style lang="scss" scoped>
@import "@/assets/PageCommon.scss";

.page-warp {
  .header-warp {
    &:after {
      height: 65px;
    }
  }

  .m-content {
     background: #f2f2f2;
    .prod-footer {
      display: flex;
      align-items: center;
      justify-content: center;

      .footer-btn {
        display: flex;
        align-items: center;
      }
    }
  }
}
</style>
